package com.eos.control.action.goods;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.eos.business.service.SysDeliverReceiptBusinessService;
import com.eos.common.tool.ConstantTool;
import com.eos.control.action.base.AbstractBaseAction;
import com.eos.orm.mybatis.model.DeliverList;
import com.hf.utils.StringUtil;

public class SaveSendExcelOfBillAction extends AbstractBaseAction {
	private static final long serialVersionUID = 574704320188428246L;
	private String allowedTypes;
	private File excelFile; // 上传的文件
	private String excelFileFileName; // 保存原始文件名
	private Integer sysProductId;
	private Integer brandId;
	private Integer activtyId;
	private Integer activtySonId;
	private Integer customerId;
	
	public File getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(File excelFile) {
		this.excelFile = excelFile;
	}

	public String getExcelFileFileName() {
		return excelFileFileName;
	}

	public void setExcelFileFileName(String excelFileFileName) {
		this.excelFileFileName = excelFileFileName;
	}

	public void setSysProductId(Integer sysProductId) {
		this.sysProductId = sysProductId;
	}

	public void setBrandId(Integer brandId) {
		this.brandId = brandId;
	}

	public void setActivtyId(Integer activtyId) {
		this.activtyId = activtyId;
	}

	public void setActivtySonId(Integer activtySonId) {
		this.activtySonId = activtySonId;
	}

	public void setCustomerId(Integer customerId) {
		this.customerId = customerId;
	}

	// 判断文件类型
	public Workbook createWorkBook(InputStream is) throws IOException {
		if (excelFileFileName.toLowerCase().endsWith("xls")) {
			return new HSSFWorkbook(is);
		}
		if (excelFileFileName.toLowerCase().endsWith("xlsx")) {
			return new XSSFWorkbook(is);
		}
		return null;
	}

	public void setAllowedTypes(String allowedTypes) {
		this.allowedTypes = allowedTypes;
	}

	@Override
	public String execute() {
		try {
			int flag = filterType(allowedTypes.split(","));
			if (flag == 0) {
				statusCode = "300";
				message = "请导入excel文件!";
			} else { 
				List<DeliverList> dlList = new ArrayList<DeliverList>();
				Workbook book = createWorkBook(new FileInputStream(excelFile));
				Sheet sheet = book.getSheetAt(0);

				CellStyle cellStyle2 = book.createCellStyle();
				DataFormat format = book.createDataFormat();
				cellStyle2.setDataFormat(format.getFormat("@"));
 
				for (int i = 1; i <= sheet.getLastRowNum(); i++) {
					Row row = sheet.getRow(i);
					row.setRowStyle(cellStyle2);
					DeliverList dl = validExcel(row);
					if (dl == null) {
						statusCode = "300";
						return SUCCESS;
					} else {
						dl.setProductId(sysProductId);
						dl.setBrandId(brandId);
						dl.setActivtyId(activtyId);
						dl.setActivtySonId(activtySonId);
						dl.setCustomerId(customerId);
						dl.setDeliverDesc("");
						dl.setStatus(ConstantTool.STATUS_OK);
						dlList.add(dl);
					}
				}

				if (dlList.size() > 0) {
					SysDeliverReceiptBusinessService sdrs = new SysDeliverReceiptBusinessService();
					String exeStatus = sdrs.batchSaveDeliverList(dlList);
					if("SUCCESS".equals(exeStatus)){
						statusCode = "200";
						message = "导入数据成功, 总共导入: " + dlList.size()+" 条!";
					}else{
						statusCode = "300";
						message = "系统繁忙, 导入数据失败!";
					}
				} else {
					statusCode = "300";
					message = "发货清单Excel没有数据, 导入失败!!";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			statusCode = "300";
			message = "系统异常, 导入发货清单Excel失败!!";
		} 
		return SUCCESS;
	}

	private DeliverList validExcel(Row row) {
		//型号/规格	颜色	  箱号	IMEI	数量	  发货日期

		DeliverList dl = new DeliverList();
		int rowNum = row.getRowNum() + 1;
		// 型号/规格
		Cell cell0 = row.getCell(0);
		if (null == cell0) {
			message = "第[ " + rowNum + " ]行, 型号/规格ID不能为空!";
			return null;
		}
		String modelId = getCellValue(cell0);
		if (!StringUtil.isNumber(modelId)) {
			message = "第[ " + rowNum + " ]行, 型号/规格ID格式错误,请输入数字!";
			return null;
		} else {
			dl.setModelId(Integer.parseInt(modelId));
		}
		//颜色栏
		Cell cell1 = row.getCell(1);
		if (cell1 == null) {
			message = "第[ " + rowNum + " ]行, 颜色ID不能为空!";
			return null;
		}
		String colorId = getCellValue(cell1);
		if (!StringUtil.isNumber(colorId)) {
			message = "第[ " + rowNum + " ]行, 颜色ID格式错误,请输入数字!";
			return null;
		} else {
			dl.setColourId(Integer.parseInt(colorId));
		}
		//箱号栏
		Cell cell2 = row.getCell(2);
		if (null == cell2) {
			message = "第[ " + rowNum + " ]行, 箱号不能为空!";
			return null;
		}
		String caseNumber   = getCellValue(cell2);
		dl.setCaseNumber(caseNumber);
		
		//产品唯一码栏
		Cell cell3 = row.getCell(3);
		if (null == cell3) {
			message = "第[ " + rowNum + " ]行, 产品唯一码不能为空!";
			return null;
		} 
		String barCode = getCellValue(cell3);
		dl.setBarCode(barCode);
		//数量栏
		Cell cell4 = row.getCell(4);
		if(null == cell4){
			message = "第[ " + rowNum + " ]行, 数量不能为空!";
		}
		String proCount = getCellValue(cell4);
		if (!StringUtil.isNumber(proCount)) {
			message = "第[ " + rowNum + " ]行, 数量的格式错误, 请输入数字!";
			return null;
		} else {
			dl.setProductCount(Integer.parseInt(proCount));
		}
		 //发货日期栏
		Cell cell5 = row.getCell(5);
		if(cell5 == null){
			message = "第[ " + rowNum + " ]行, 发货日期不能为空!";
			return null;
		}
		String deliverTime = getCellValue(cell5);
		dl.setDeliverTime(deliverTime);
		return dl;
	}

	public String getCellValue(Cell cell) {
		cell.setCellType(HSSFCell.CELL_TYPE_STRING);
		String val = cell.getStringCellValue();
		return val;
	}

	/**
	 * 判断上传的是否为excel; 0: 否; 1: 是.
	 * @param types
	 * @return
	 */
	public int filterType(String[] types) {
		if (null != excelFile) {
			String fileName = excelFileFileName;
			String suffix = "";
			if ((fileName != null) && (fileName.length() > 0)) {
				int dot = fileName.lastIndexOf('.');
				if ((dot > -1) && (dot < (fileName.length() - 1))) {
					suffix = fileName.substring(dot);
				}
			}
			for (String type : types) {
				if (!StringUtil.isNumber(suffix)
						&& type.equalsIgnoreCase(suffix)) {
					return 1;
				}
			}
		}
		return 0;
	}
}
